<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\Admin;
use plugin\admin\app\model\AdminRole;
use plugin\admin\app\service\v1\UserService;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * 会员管理
 */
class V1UserController extends Crud
{

    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = ['selectNew'];

    /**
     * 需要登录无需权的方法
     * @var array
     */
    protected $noNeedAuth = [
        'select'
    ];

    /**
     * @var Admin
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Admin;
    }

    /**
     * 浏览
     * @return Response
     * @throws Throwable
     */
    public function index(): Response
    {
        $admin = admin();
        return view('v1-user/index', compact('admin'));
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $admin = admin();
        if ($admin['user_status'] == CommonConstant::DEFAULT_2) {
            $where['invitation_id'] = $admin['id'];
        }
        $where['user_status'] = CommonConstant::DEFAULT_2;
        $query = $this->doSelect($where, $field, $order);
        $query->withCount([
            'invitation as invitation_total' => function ($query) {
                $query->where('user_status', CommonConstant::DEFAULT_2)
                    ->select($query->raw('count(id)'));
            },
            'orderNode as order_node_total' => function ($query) {
                $query->where('deleted', CommonConstant::DELETE_0)
                    ->whereIn('refund_status', [CommonConstant::DEFAULT_0, CommonConstant::DEFAULT_3])
                    ->select($query->raw("count(id)"));
            },
        ]);
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if ($admin['user_status'] == CommonConstant::DEFAULT_2) {
            foreach ($items as &$item) {
                $item['mobile'] = substr_replace($item['mobile'], '****', 3, 4);
            }
        }
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
//        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $username = $request->post('username');
            $password = $request->post('password');
            $password_confirm = $request->post('password_confirm');
            $qq = $request->post('qq');
            $weixin = $request->post('weixin');
            $mobile = $request->post('mobile');
            $code = $request->post('code');
            $invitation = $request->post('invitation');
            $link_id = $request->post('link_id');
            $params = compact('username', 'password', 'password_confirm', 'qq', 'weixin', 'mobile', 'code', 'invitation', 'link_id');
            if (!$username) {
                return $this->json(1, '请输入用户名！');
            }
            if (!$password) {
                return $this->json(1, '请输入密码！');
            }
            if ($password_confirm !== $password) {
                return $this->json(1, '两次密码输入不一致!');
            }
            if (!$mobile) {
                return $this->json(1, '请输入手机号!');
            }
            if (!$qq) {
                return $this->json(1, '请输入QQ!');
            }
            if (!$weixin) {
                return $this->json(1, '请输入微信!');
            }
            UserService::registerUser($params, CommonConstant::DEFAULT_0);
            return $this->json(0, '添加成功');
        }
        $admin = admin();
        $invitation = $admin['id'] == 1 ? '' : $admin['username'];
        return view('v1-user/insert', ['admin' => $admin, 'invitation' => $invitation]);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $primary_key = $this->model->getKeyName();
        $ids = $request->post($primary_key);
        if (!$ids) {
            return $this->json(0);
        }
        $ids = (array)$ids;
        if (in_array(admin_id(), $ids)) {
            return $this->json(1, '不能删除自己');
        }
        if (!Auth::isSuperAdmin() && array_diff($ids, Auth::getScopeAdminIds())) {
            return $this->json(1, '无数据权限');
        }
        $this->model->whereIn($primary_key, $ids)->each(function (Admin $admin) {
            $admin->delete();
        });
        AdminRole::whereIn('admin_id', $ids)->each(function (AdminRole $admin_role) {
            $admin_role->delete();
        });
        return $this->json(0);
    }

    /**
     * 变动余额
     * @param Request $request
     * @return Response
     */
    public function money(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $primary_key = $this->model->getKeyName();
            $ids = $request->post($primary_key);
            $change_type = $request->post('change_type');
            $money = $request->post('money');
            if (!$ids) {
                return $this->json(1, '用户参数错误');
            }
            if (!array_key_exists($change_type, CommonConstant::get_change_type_list())) {
                return $this->json(1, '请选择正确的变动类型！');
            }
            if (!is_numeric($money) || $money < 1) {
                return $this->json(1, '变动金额不能小于1！');
            }

            $lock = Util::basicSetnx('money_user_'.admin_id(),1);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $admin = admin();
            if ($admin['user_status'] == CommonConstant::DEFAULT_1) {
                $where['id'] = $ids;
            } else {
                if ($admin['money'] < $money) {
                    return $this->json(1, '你的余额不足！',$admin);
                }
                $where['id'] = $ids;
                $where['invitation_id'] = $admin['id'];
            }
            $user = Admin::where($where)->first(['id', 'username', 'money']);
            if (!$user) {
                return $this->json(1, '会员信息不存在或已删除');
            }

            $memo = $change_type == CommonConstant::DEFAULT_10 ? '给【' . $user['username'] . '】充值 ' . $money . ' 个金币' : '给【' . $user['username'] . '】扣除 ' . $money . ' 个金币';
            $logDataAdmin = [];
            if ($admin['user_status'] == CommonConstant::DEFAULT_1) {
            } else {
                $logDataAdmin = [
                    'admin_id' => $admin['id'],
                    'admin_name' => $admin['username'],
                    'user_id' => $admin['id'],
                    'user_name' => $admin['username'],
                    'type' => CommonConstant::MONEY_LOG_TYPE_0,
                    'change_type' => CommonConstant::DEFAULT_20,
                    'money' => $money,
                    'memo' => $memo,
                ];
            }
            $logData = [
                'admin_id' => $admin['id'],
                'admin_name' => $admin['username'],
                'user_id' => $ids,
                'user_name' => $user['username'],
                'type' => CommonConstant::MONEY_LOG_TYPE_0,
                'change_type' => $change_type,
                'money' => $money,
                'memo' => $memo,
            ];
            Util::db()->transaction(function () use ($logDataAdmin, $admin, $logData, $ids, $user) {
                if($logDataAdmin){
                    UserService::money($logDataAdmin, $admin['id'], []);
                    UserService::money($logData, $ids, [], ['type' => 'recharge']);
                } else{
                    UserService::money($logData, $ids, []);
                }
            });
            return $this->json(0, '修改成功');
        }
        $admin = admin();
        return view('v1-user/money', compact('admin'));
    }

    /**
     * 变动佣金
     * @param Request $request
     * @return Response
     */
    public function commission(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $primary_key = $this->model->getKeyName();
            $ids = $request->post($primary_key);
            if (!$ids) {
                return $this->json(1, '用户参数错误');
            }
            $change_type = $request->post('change_type');
            $money = $request->post('money');
            if (!array_key_exists($change_type, CommonConstant::get_change_type_list())) {
                return $this->json(1, '请选择正确的变动类型！');
            }
            if (!is_numeric($money) || $money < 1) {
                return $this->json(1, '变动金额不能小于1！');
            }

            $lock = Util::basicSetnx('commission_user_'.admin_id(),1);
            if (!$lock) {
                return json(['code' => 1, 'msg' => '系统繁忙，请稍后再试！']);
            }

            $user = Admin::where('id', $ids)->first(['id', 'username', 'money']);
            if (!$user) {
                return $this->json(1, '会员信息不存在或已删除');
            }

            $admin = admin();
            $memo = $change_type == CommonConstant::DEFAULT_10 ? '给【' . $user['username'] . '】充值 ' . $money . ' 个佣金' : '给【' . $user['username'] . '】扣除 ' . $money . ' 个金佣金';
            $logData = [
                'admin_id' => $admin['id'],
                'admin_name' => $admin['username'],
                'user_id' => $ids,
                'user_name' => $user['username'],
                'type' => CommonConstant::MONEY_LOG_TYPE_0,
                'change_type' => $change_type,
                'money' => $money,
                'memo' => $memo,
            ];
            Util::db()->transaction(function () use ($logData, $user) {
                UserService::commission($logData, $logData['user_id'], [], ['type' => 'commission']);
            });
            return $this->json(0, '修改成功');
        }
        $admin = admin();
        return view('v1-user/commission', compact('admin'));
    }

    /**
     * 修改上级
     * @param Request $request
     * @return Response
     **/
    public function invitation(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $primary_key = $this->model->getKeyName();
            $ids = $request->post($primary_key);
            if (!$ids) {
                return $this->json(1, '用户参数错误');
            }
            $invitation_id = (integer)$request->post('invitation_id', 0);
            if ($invitation_id) {
                $invitationInfo = Admin::where('id', $invitation_id)->first(['id', 'username']);
                if (!$invitationInfo) {
                    return $this->json(1, '会员信息不存在或已删除');
                }
                $data['invitation_id'] = $invitation_id;
                $data['invitation'] = $invitationInfo['username'];
            } else {
                $data['invitation_id'] = $invitation_id;
                $data['invitation'] = '';
            }

            Util::db()->transaction(function () use ($ids, $data) {
                Admin::where('id', $ids)->update($data);
            });
            return $this->json(0, '修改成功');
        }
    }

    /**
     * 权限设置
     * @return Response
     * @throws Throwable
     **/
    public function user_extend(): Response
    {
        return view('v1-user/user_extend');
    }


    /**
     * 资金记录-查询操作人
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function selectNew(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $limit = (int)$request->input('limit', 100);
        $name = $request->input('name', '');

        $where = [];
        if ($name) {
            $where['username'] = $name;
        }
        $query = $this->model->where($where)
            ->select(['id', 'username as name'])
            ->orderBy('id', 'desc');
        $paginator = $query->paginate($limit);
        return json(['code' => 0, 'msg' => 'ok', 'data' => $paginator]);
    }

}
